package com.hjx.windowtool.cmd;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.swing.AbstractListModel;

public class StringListModel extends AbstractListModel<String> {
	

	private List<String> list=new ArrayList<>();
	private List<String> listSource=new ArrayList<>();
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Predicate<? super String> filter;
	
	public StringListModel() {
	}
	
	public StringListModel(List<String> listSource) {
		this.listSource=listSource;
	}

	@Override
	public int getSize() {
		return list.size();
	}

	@Override
	public String getElementAt(int index) {
		return list.get(index);
	}
	
	public void refresh() {
		if (filter!=null) {
			list=listSource.stream().filter(filter).collect(Collectors.toList());
		}else {
			this.list = listSource;
		}
		fireContentsChanged(this, 0, 0);
	}
	
	public void filter(Predicate<? super String> filter) {
		this.filter = filter;
		refresh();
	}

	public List<String> getListSource() {
		return listSource;
	}

	public void setListSource(List<String> listSource) {
		this.listSource = listSource;
		refresh();
	}

	public void add(String s) {
		listSource.add(s);
		refresh();
	}

	public void remove(int index) {
		if(index>listSource.size()-1) {
			return;
		}
		listSource.remove(index);
		refresh();
	}
}